package com.wwj.auction.oss.controller;

import com.wwj.auction.common.result.R;
import com.wwj.auction.common.result.exception.BusinessException;
import com.wwj.auction.oss.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * 文件服务
 *
 * @author wwj
 */
@RestController
@RequestMapping("/oss/file")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 上传文件
     *
     * @param file
     * @param module
     * @return
     */
    @PostMapping("/upload")
    public R upload(
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "module", required = false) String module) {
        try {
            // 获取文件流
            InputStream inputStream = file.getInputStream();
            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            // 文件上传
            String url = fileService.upload(inputStream, module, originalFilename);
            return R.ok().message("文件上传成功").data("url", url);
        } catch (IOException e) {
            throw new BusinessException("文件上传失败");
        }
    }

    /**
     * 删除指定文件
     *
     * @param url
     * @return
     */
    @DeleteMapping("/remove")
    public R remove(@RequestParam("url") String url) {
        fileService.removeFile(url);
        return R.ok().message("文件删除成功");
    }
}
